package scenery;

import com.crunch.core.Renderer;
import com.crunch.graphics.gpu.GpuState;
import com.crunch.graphics.gpu.GpuTexture;

/**
 * Instance of a background layer which can be rendered.
 */
public class BackgroundLayerInstance {
	public BackgroundLayerInstance(BackgroundLayer backgroundLayer, GpuTexture texture, Renderer renderer) {
		this.renderer = renderer;
		this.backgroundLayer = backgroundLayer;
		setTexture(texture);
	}

	// queues resources to be released - should not make any more modifying calls after this
	public void release() {
		renderer.queueCommand(new Renderer.Command() {
			@Override
			public void execute(GpuState gpuState) {
				if (texture != null) {
					texture.release();
				}
			}
		});
	}

	public BackgroundLayer getBackgroundLayer() {
		return backgroundLayer;
	}

	public void setTexture(GpuTexture texture) {
		final GpuTexture texOld = this.texture;
		final GpuTexture texNew = texture;
		this.texture = texture;
		renderer.queueCommand(new Renderer.Command() {
			@Override
			public void execute(GpuState gpuState) {
				if (texOld != null) {
					texOld.release();
				}
				if (texNew != null) {
					texNew.acquire();
				}
			}
		});
	}

	public GpuTexture getTexture() {
		return texture;
	}

	private BackgroundLayer backgroundLayer;
	private GpuTexture texture;
	private Renderer renderer;
}
